import 'package:flutter_app/http/core/dio_adapter.dart';
import 'package:flutter_app/http/core/hi_error.dart';
import 'package:flutter_app/http/core/hi_net_adapter.dart';
import 'package:flutter_app/http/core/mock_adapter.dart';
import 'package:flutter_app/http/request/base_request.dart';

class HiNet {
  HiNet._();

  static HiNet _instance;

  static HiNet getInstance() {
    _instance ??= HiNet._();
    return _instance;
  }
  ///
  Future fire(BaseRequest request) async {
    HiNetResponse response;
    var error;
    try {
      response = await send(request);
    } on HiNetError catch (e) {
      ///系统定义的异常
      error = e;
      response = e.data;
      printLog(e.message);
    } catch (e) {
      ///其它异常
      error = e;
      printLog(e);
    }
    if (response == null) {
      printLog(error);
    }
    if (response == null) {
      printLog(error);
    }
    ///返回请求结果
    var result = response?.data;
    var status=response?.statusCode;
    switch(status){
      case 200:
        return result;
      case 401:
        throw NeedLogin();
      case 403:
        throw NeedAuth(result.toString(),date: result);
      default:
        throw HiNetError(status, result.toString(),data: result);
    }
  }
  ///打印接口请求基础信息
  Future<dynamic> send<T>(BaseRequest request) async {
    printLog('url:${request.url()}');
    HiNetAdapter hiNetAdapter=DioAdapter();
    return hiNetAdapter.send(request);
  }
  ///日志基础封装，便于识别
  void printLog(log) {
    print('hi_net:${log.toString()}');
  }
}
